import { ref } from 'vue'
import SockJS from 'sockjs-client'
import { Stomp } from '@stomp/stompjs'

let stompClient = null
let subscription = null

export function useWebSocket() {
  const connected = ref(false)
  const connecting = ref(false)

  /**
   * 连接 WebSocket
   * @param {Function} onMessage 消息回调函数
   */
  const connect = (onMessage) => {
    if (connected.value || connecting.value) {
      console.log('WebSocket 已连接或正在连接中')
      return
    }

    connecting.value = true

    try {
      // 获取 token
      const token = localStorage.getItem('token')
      if (!token) {
        console.warn('未找到 token，无法连接 WebSocket')
        connecting.value = false
        return
      }

      // 从 token 中解析用户 ID
      const userId = getUserIdFromToken(token)
      if (!userId) {
        console.warn('无法从 token 中解析用户 ID')
        connecting.value = false
        return
      }

      // 创建 WebSocket 连接
      const baseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
      const wsURL = baseURL.replace('http', 'ws') + '/ws'
      
      console.log('正在连接 WebSocket：', wsURL)

      const socket = new SockJS(wsURL)
      stompClient = Stomp.over(socket)

      // 禁用调试日志（可选）
      stompClient.debug = () => {}

      // 连接到 WebSocket
      stompClient.connect(
        {},
        (frame) => {
          console.log('WebSocket 连接成功：', frame)
          connected.value = true
          connecting.value = false

          // 订阅用户专属频道
          const destination = `/topic/user/${userId}`
          console.log('订阅频道：', destination)

          subscription = stompClient.subscribe(destination, (message) => {
            try {
              const data = JSON.parse(message.body)
              console.log('收到 WebSocket 消息：', data)
              
              // 调用回调函数
              if (onMessage && typeof onMessage === 'function') {
                onMessage(data)
              }
            } catch (error) {
              console.error('解析 WebSocket 消息失败：', error)
            }
          })
        },
        (error) => {
          console.error('WebSocket 连接失败：', error)
          connected.value = false
          connecting.value = false

          // 5秒后重连
          setTimeout(() => {
            console.log('尝试重新连接 WebSocket...')
            connect(onMessage)
          }, 5000)
        }
      )
    } catch (error) {
      console.error('WebSocket 连接异常：', error)
      connected.value = false
      connecting.value = false
    }
  }

  /**
   * 断开 WebSocket 连接
   */
  const disconnect = () => {
    if (subscription) {
      subscription.unsubscribe()
      subscription = null
    }

    if (stompClient && stompClient.connected) {
      stompClient.disconnect(() => {
        console.log('WebSocket 已断开')
        connected.value = false
      })
    }
  }

  /**
   * 从 JWT token 中解析用户 ID
   */
  const getUserIdFromToken = (token) => {
    try {
      // JWT token 格式：header.payload.signature
      const parts = token.split('.')
      if (parts.length !== 3) {
        return null
      }

      // 解码 payload（Base64）
      const payload = JSON.parse(atob(parts[1]))
      return payload.userId || payload.sub || null
    } catch (error) {
      console.error('解析 token 失败：', error)
      return null
    }
  }

  return {
    connected,
    connecting,
    connect,
    disconnect
  }
}

